package middleware

import (
	"fmt"
	"ginstudydemo.com/main/service"
	"github.com/gin-gonic/gin"
)

type IJwtV5 interface {
	JWTAuth()
}
type JwtV5 struct{}

func NewJwtV5() *JwtV5 {
	return &JwtV5{}
}

// JWTAuth 验证token中间件
func (j JwtV5) JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		//header获取token
		token := c.Request.Header.Get("Authorization")
		if token == "" {
			service.ReturnErr(c, "4001", "未携带token")
			c.Abort()
			return
		}

		// 检查 token 是否在黑名单中
		isBlacklisted, svErr := service.NewAuthService().IsTokenBlacklisted(token)
		if svErr != nil {
			service.ReturnErr(c, "4001", "Failed to check token blacklist")
			c.Abort()
			return
		}
		if isBlacklisted {
			service.ReturnErr(c, "4001", "Token has been blacklisted")
			c.Abort()
			return
		}

		// 校验token
		claims, tokenErr := service.NewJwtV5().DecodeUserToken(token)
		// token 验证失败
		if tokenErr != nil {
			fmt.Println(tokenErr.Error())
			//如果不是token过期的原因，直接返回错误
			service.ReturnErr(c, "4001", "Jwt:token验证失败")
			c.Abort()
			return

		}

		fmt.Println(claims)
		// 判断payload解码是否成功
		if claims == nil {
			service.ReturnErr(c, "4001", "token解码失败")
			c.Abort()
			return
		}
		c.Set("claims", claims) // 将续签后的 claims 保存到 context 中
		c.Next()
	}
}
